﻿let configpath = require("./getConfig").ev.path;
let config1 = require(configpath);
let cluster = require('cluster');
let exec = require("./Multithreading").exec;

if (!config1.list)
    throw console.log("配置错误");
let serverList = config1.list;

if (cluster.isMaster) {//主线程
    mainProcess();
} else {
    //initchild();
    console.log("child pid start")
}
/*function initchild() {
    cluster.worker.on('message',  (msg) => {
         console.log("onmessage>>")
        console.log(arguments);
        //  debugger
        if (msg && msg.type == "createServer")
            createServerBy(msg.val)
    });
    console.log(arguments);
}*/


function monitor() {
    setInterval(function report() {
        process.send({ memory: process.memoryUsage(), process: process.pid });
    }, 10000);
}
function forkWorker(listener) {//参数回调
    let worker = cluster.fork();
    console.log('worker [%d] has been created', worker.process.pid);
    worker.on('message', listener);
    return worker;
};

function mainProcess() {
    console.log(JSON.stringify(serverList));
    for (var index = 0, len = config1.list.length * 2; index < len; index++) {
        /*        let s = forkWorker(function(){
                    console.log("主线程回掉")
                });*/
        exec("node ./childprocess " + JSON.stringify(JSON.stringify({ index })))
        //console.log("子进程启动：" + s.process.pid);
        /*        s.send({
                    type: 'createServer',
                    value: index
                });*/
    }

}
//Cluster收到子进程退出消息
cluster.on('exit', function (worker, code, signal) {
    console.log('worker [%d] died %s, fork a new one.',
        worker.process.pid, code || signal);
    //forkWorker(workerListener);
});
//Cluster收到子进程运行消息
cluster.on('online', function (worker) {
    console.log('worker [%d] is running.', worker.process.pid);
});
process.on('uncaughtException', function () {

});